﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Sushi.Core;
using Sushi.Sample.Service.Data.Properties;
using Exception = System.Exception;//needed because sushi also has an exception class

namespace Sushi.Sample.Service.Data
{
   public class UsageReportRepository : IUsageReportRepository
   {
      public List<CounterXMLFile> FillFileList(string directory)
      {
         var files = new List<CounterXMLFile>();
         foreach (var fileName in Directory.GetFiles(directory))
         {
            try
            {
               files.Add(new CounterXMLFile(fileName));
            }
            catch //ignore any errors - bad files not added to list
            {
            }
         }
         return files;
      }


      public Report[] GetUsageReports(ReportRequest request)
      {
         //if release is not "" or "1" then throw an error for unsupported release.
         if (!((request.ReportDefinition.Release == "") || (request.ReportDefinition.Release == "1")))
				throw new SushiServiceException(string.Format("Request specifies an unsupported release value: {0}. Only release 1 is supported at this time.", request.ReportDefinition.Release));


         string dataPath = Settings.Default.CounterFilePath;
         var files = FillFileList(dataPath);

         var customerReports = from file in files
                 where
						  (file.CustomerId == request.CustomerReference.ID) && 
                    (file.RunDate >= request.ReportDefinition.Filters.UsageDateRange.Begin) &&
						  (file.RunDate <= request.ReportDefinition.Filters.UsageDateRange.End) &&
                    (
                      //if no name is specified, get all the reports that match date range & customer id
                      (request.ReportDefinition.Name == "") ||
							 (file.ReportType.Equals(request.ReportDefinition.Name, StringComparison.OrdinalIgnoreCase))
                    )
                 select file;

         var reports = new Reports();


         foreach (var reportFile in customerReports)
         {
            var report = new Report();
            report.Created = reportFile.RunDate;
            report.CreatedSpecified = true;
            var reportCustomer = new ReportCustomer
                              {
                                 ID = request.CustomerReference.ID,
                                 ReportItems = reportFile.ReadReportItems()
                              };

            report.Customer = new[] { reportCustomer };
            reports.Add(report);
         }


         return reports.ToArray();
      }
   }
}
